<template>
  <div>
    <a-row class='mytitle'>
      <!-- <i class="icon icon-CHKDSK16l title-icon-style"></i> -->
      {{ $t('Disk-check') }}
    </a-row>

    <NoAuthPage v-showNoAuth="'E8-1'" />

    <div class="content-box" v-userAuth="'E8-1'">
      <!-- v-userAuth="'E8'" -->
      <div class="top-check-content" v-if="!isChecking">
        <div class="top-tip">
          <img src="../../../../static/images/disk_check/16_f_ic_tips.png" alt="tip_img" class="tip-img" />
          <span v-if="$store.state.language == 'zh'">注：磁盘检测只能针对普通的SSD盘及HDD磁盘，<span
              class="time-tip text-weight">Nvme</span>磁盘无法进行检测。</span>
          <span v-else>Note: disk detection can only be used for ordinary SSD disks and HDD disks, and <span
              class="time-tip text-weight">nvme</span> disks cannot be detected.</span>
        </div>
        <div class="split-line"></div>
        <div class="check-type-box" v-for="(item, index) in check_types" :key="index">
          <a-row>
            <a-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6" :xxl="4">
              <img :src="item.img" alt="img_desc" style="width:128px;height:128px" />
            </a-col>
            <a-col :xs="18" :sm="18" :md="18" :lg="18" :xl="18" :xxl="20">
              <div>
                <span class="check-title">{{ item.name }}</span>
                <a-button v-userAuth="'E8-2'" shape="round" :class="index == 0 ? 'quick-btn' : 'deep-btn'"
                  @click="handleCheck(index)">{{ $t('Immediately-detect') }}</a-button>
              </div>
              <a-tooltip v-if="$store.state.language == 'en' && index != 0">
                <template slot="title">{{ item.describe }}</template>
                <div class="check-desc en-check-desc">{{ item.describe }}</div>
              </a-tooltip>
              <div v-else class="check-desc">{{ item.describe }}</div>
              <div v-if="$store.state.language == 'zh'">
                <span>{{ $t('Take-reference') }}</span><!--耗时参考-->
                <span class="check-hhdtip">{{ item.hhdDec }}</span>
                <span class="check-ssdtip">{{ item.ssdDec }}</span>
              </div>
              <div v-else>
                <span>{{ $t('Take-reference') }}</span><!--耗时参考-->
                <span class="check-hhdtip">{{ item.hhdDec_en }}</span>
                <span class="check-ssdtip">{{ item.ssdDec_en }}</span>
              </div>
            </a-col>
          </a-row>
        </div>
      </div>
      <!--检测中-->
      <div class="top-check-content2" v-else>
        <div class="check-type-box">
          <a-row>
            <a-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6" :xxl="4">
              <a-progress type="circle" :percent="checkingPercent" strokeColor="#059db3" />
              <!-- <canvas id="mycanvas" width="150" height="150"></canvas> -->
            </a-col>
            <a-col :xs="18" :sm="18" :md="18" :lg="18" :xl="18" :xxl="20">
              <div>
                <span v-if="checkType == 0" class="check-title">{{ $t('Quick-check') }}</span>
                <span v-else class="check-title">{{ $t('Deep-check') }}</span>
                <a-button v-userAuth="'E8-3'" shape="round" class="quick-btn"
                  @click="handleStopCheck">{{ $t('Break-detect') }}</a-button>
              </div>
              <div class="check-desc">
                <span v-if="$store.state.language == 'zh'">检测已进行</span>
                <span v-else>Detection has been carried out</span>
                <span class="time-tip">{{ checkingTime }}</span>
                <!-- ，预计将于<span class="time-tip">2022年xxx</span>结束 -->
              </div>
            </a-col>
          </a-row>
        </div>
        <div class="check-type-box2">
          <a-row>
            <a-col :span="1"><img src="../../../../static/images/disk_check/16_f_ic_tips.png" alt="tip_img"
                class="tip-img" /></a-col>
            <a-col :span="23">
              <div v-if="$store.state.language == 'zh'">
                您已选择<span class="time-tip" v-if="checkType == 0">快速检测</span><span class="time-tip"
                  v-else>深度检测</span>模式，系统正在执行检测，请耐心等候，在此期间您可以离开界面或进行其他操作，扫描完毕后系统会自动生成检测报告，您无需一直等待。如您选择中断检测或直接退出账号登录，则本次检测不会输出检测结果，下次检测您需要从头开始。
              </div>
              <div v-else>
                During this period, you can leave the screen or perform other operations. After the scan is complete,
                the
                system automatically generates a detection report. You do not need to wait all the time. If you choose
                to
                <span class="time-tip" v-if="checkType == 0">interrupt the detection</span><span class="time-tip"
                  v-else>deep
                  the detection</span> or log out of your account directly, the detection result will not be output this
                time.
                You need to start from the beginning next time.
              </div>
            </a-col>
          </a-row>
        </div>
      </div>

      <!--检测表格-->
      <a-spin :spinning="dataSpinning">
        <div class="bottom-check-record">
          <!-- :style="(isChecking && screenWidth<1920)?{height:'450px'}:(isChecking && screenWidth>=1920)?{height:'640px'}:{}" -->
          <div class="disk-check-record-title">
            <span>{{ $t('Disk-detection-record') }}</span>
          </div>
          <div class="check-table-box">
            <div class="check-filter-box">
              <span>
                {{ $t('Display-fault-records') }}：<a-checkbox v-model="error_check_value"
                  @change="changeErrorCheck"></a-checkbox>
              </span>
              <span>
                {{ $t('Show-collection') }}：<a-checkbox v-model="collect_check_value"
                  @change="changeCollectCheck"></a-checkbox>
              </span>
              <span>
                {{ $t('Detect-patterns') }}：
                <a-radio-group v-model="check_mode" button-style="solid" @change="changeCheckMode">
                  <a-radio-button v-for="(item, index) in radio_values" :value="item.value"
                    :key="index">{{ item.name }}</a-radio-button>
                </a-radio-group>
              </span>
              <div style="line-height:32px">{{ $t('Check-end-time') }}：</div>
              <div>
                <a-range-picker v-model="checkTime" show-time :placeholder="[$t('Start-date'), $t('End-date')]"
                  @ok="handleCheckEndTime" @change="handleClearTime" format="YYYY-MM-DD HH:mm:ss"
                  :locale="rangePickerLocal" style="width:100%"></a-range-picker>
                <!-- @change="changeCheckTime" -->
              </div>
            </div>
            <div class="check-table">
              <a-table :columns="columns" :dataSource="tableData" :loading="tableLoading" size="small" bordered
                :pagination='pagination' rowKey="id" :locale="defaultSetting">
                <span slot="id" slot-scope="text, record">
                  <img v-if="record.top == 1" src="../../../../static/images/disk_check/16_f_ic_stick.png"
                    style="margin-right:5px" alt="stick_img" class="tip-img" />
                  <img v-if="record.star == 1" src="../../../../static/images/disk_check/16_f_ic_collect.png"
                    style="margin-right:5px" alt="collect_img" class="tip-img" />
                  {{ text }}
                  <img v-if="record.read_status == 0" src="../../../../static/images/disk_check/pic_new.png"
                    alt="new_img" style="width:32px;height:16px;" />
                </span>
                <template slot="time" slot-scope="text, record">
                  <span v-if="$store.state.language == 'zh'">{{ text }}</span>
                  <span v-else>{{ text.replace(/天/, 'day').replace(/小时/, 'hours').replace(/分钟/, 'minutes') }}</span>
                </template>
                <template slot="mode" slot-scope="text, record">
                  <span v-if="record.type == 0">{{ $t('Quick-check') }}</span>
                  <span v-else>{{ $t('Deep-check') }}</span>
                </template>
                <template slot="problem" slot-scope="text, record">
                  <div v-if="record.status == 0"><!--检测中-->
                    <span class="purple-circle"></span><span>{{ $t('Checking') }}</span>
                  </div>
                  <div v-else-if="record.status == 1"><!--正常结束-->
                    <span class="green-circle"></span><span>{{ $t('Normal-end') }}</span>
                  </div>
                  <div v-else><!--2用户中断-->
                    <span class="red-circle"></span><span>{{ $t('User-interrupt') }}</span>
                  </div>
                </template>
                <template slot="result" slot-scope="text, record">
                  <div v-if="record.result == 0"><!--未发现故障-->
                    <span class="green-circle"></span><span>{{ $t('No-fault-found') }}</span>
                  </div>
                  <div v-else-if="record.result == 2"><!--未完成检测-->
                    <span class="green-circle"></span><span>{{ $t('Incomplete-detection') }}</span>
                  </div>
                  <div v-else-if="record.result == 3"> <!-- 未能检测 -->
                    <template>
                      <a-tooltip>
                        <template slot="title">{{ $t('兼容问题检测未完成')}}</template>
                        <span class="red-circle"></span><span>{{ $t('Failure to detect') }}</span>
                      </a-tooltip>
                    </template>
                  
                  </div>
                  <div v-else><!--发现故障-->
                    <span class="red-circle"></span><span>{{ $t('Fault-found') }}</span>
                  </div>
                </template>
                <div slot="action" slot-scope="text, record">
                  <span class="oper-btn">
                    <a-tooltip v-if="record.status != 2"><!--详情-->
                      <template slot="title">{{ $t('Detail') }}</template>
                      <img src="../../../../static/images/disk_check/16_f_ic_view.png"
                        @click="showDetail(record, 'read', 1)" alt="view_img" class="tip-img" />
                    </a-tooltip>
                    <img v-else src="../../../../static/images/disk_check/16_f_ic_view_grey.png"
                      style="cursor:not-allowed" alt="view_grey_img" class="tip-img" />
                  </span>
                  <span class="oper-btn" v-if="isShowTopAndCollect">
                    <a-tooltip v-if="record.top == 0"><!--置顶-->
                      <template slot="title">{{ $t('Topping') }}</template>
                      <img src="../../../../static/images/disk_check/16_f_ic_stick.png"
                        @click="toOperateStatus(record, 'top', 1)" alt="stick_img" class="tip-img" />
                    </a-tooltip>
                    <a-tooltip v-else><!--取消置顶-->
                      <template slot="title">{{ $t('Cancel-topping') }}</template>
                      <img src="../../../../static/images/disk_check/16_f_ic_cancelstick.png"
                        @click="toOperateStatus(record, 'top', 0)" alt="no_stick_img" class="tip-img" />
                    </a-tooltip>
                  </span>
                  <span class="oper-btn" v-if="isShowTopAndCollect">
                    <a-tooltip v-if="record.star == 0"><!--收藏-->
                      <template slot="title">{{ $t('Collection') }}</template>
                      <img src="../../../../static/images/disk_check/16_l_ic_collect.png"
                        @click="toOperateStatus(record, 'star', 1)" alt="collect_img" class="tip-img" />
                    </a-tooltip>
                    <a-tooltip v-else><!--取消收藏-->
                      <template slot="title">{{ $t('Cancel-favorites') }}</template>
                      <img src="../../../../static/images/disk_check/16_f_ic_collect.png"
                        @click="toOperateStatus(record, 'star', 0)" alt="collect_img" class="tip-img" />
                    </a-tooltip>
                  </span>
                  <span class="oper-btn" v-userAuth="'E8-4'">
                    <a-tooltip><!--删除-->
                      <template slot="title">{{ $t('Delete') }}</template>
                      <img src="../../../../static/images/disk_check/16_f_ic_delete.png" @click="delCheckRecord(record)"
                        alt="del_img" class="tip-img" />
                    </a-tooltip>
                  </span>
                </div>
              </a-table>
            </div>
          </div>
        </div>
      </a-spin>

      <SelectDiskDialog :visible="check_dialog" :checkType="checkType" @closeDialog="closeDialog"
        :checkDisks="checkDisks" @isCheckingDisk="isCheckingDisk" />
      <RecordDetail :visible="record_detail_dialog" @closeDrawer="closeDrawer" :target="targetCheckRecord"
        :detailSpinning="detailSpinning" @refreshRecordData="getDiskCheckRecord" />
    </div>
  </div>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
import SelectDiskDialog from '@/views/operation/disk_check/oper/SelectDiskDialog'
import RecordDetail from '@/views/operation/disk_check/oper/RecordDetail'
import { getTimestampFromString } from '@/untils/formatTime'
import request from '@/request/request'
import NoAuthPage from '@/components/common/NoAuthPage'

export default {
  name: "DiskCheck",
  components: { EmptyData, SelectDiskDialog, RecordDetail, NoAuthPage },
  data() {
    return {
      check_types: [
        {
          name: this.$t('Quick-check'),
          describe: this.$t('Quick-check-dec'),
          hhdDec: '8TB的HDD耗时：2分钟',
          ssdDec: '520GB的SSD耗时：1分钟',
          hhdDec_en: '8TB HDD time: 2 minutes',
          ssdDec_en: '520GB SSD time: 1 minute',
          img: require('../../../../static/images/disk_check/128_f_ic_quickcheck.png')
        },
        {
          name: this.$t('Deep-check'),
          describe: this.$t('Deep-check-dec'),
          hhdDec: '8TB的HDD耗时：35分钟',
          ssdDec: '520GB的SSD耗时：2分钟',
          hhdDec_en: '8TB HDD time: 35 minutes',
          ssdDec_en: '520GB SSD time: 2 minutes',
          img: require('../../../../static/images/disk_check/128_f_ic_depthcheck.png')
        },
      ],
      error_check_value: false,
      collect_check_value: false,
      check_mode: 'all',
      radio_values: [
        { name: this.$t('All'), value: 'all' },
        { name: this.$t('Quick-check'), value: 0 },
        { name: this.$t('Deep-check'), value: 1 },
      ],
      checkTime: [],
      check_end_time_string: [],
      rangePickerLocal: {
        "lang": {
          "placeholder": "Select date",
          "rangePlaceholder": ["Start date", "End date"],
          "today": "Today",
          "now": "Now",
          "backToToday": "Back to today",
          "ok": this.$t('Sure'),
          "clear": "Clear",
          "month": "Month",
          "year": "Year",
          "timeSelect": this.$t('Select-time-picker'),
          "dateSelect": this.$t('Select-date-picker'),
          "monthSelect": "Choose a month",
          "yearSelect": "Choose a year",
          "decadeSelect": "Choose a decade",
          "yearFormat": "YYYY",
          "dateFormat": "M/D/YYYY",
          "dayFormat": "D",
          "dateTimeFormat": "M/D/YYYY HH:mm:ss",
          "monthFormat": "MMMM",
          "monthBeforeYear": true,
          "previousMonth": "Previous month (PageUp)",
          "nextMonth": "Next month (PageDown)",
          "previousYear": "Last year (Control + left)",
          "nextYear": "Next year (Control + right)",
          "previousDecade": "Last decade",
          "nextDecade": "Next decade",
          "previousCentury": "Last century",
          "nextCentury": "Next century"
        },
      },
      defaultSetting: { emptyText: <EmptyData /> },
      columns: [
        { title: this.$t('Record') + 'ID', dataIndex: 'record_id', key: 'record_id', scopedSlots: { customRender: 'id' }, width: 200, ellipsis: true, },
        { title: this.$t('Start-time'), dataIndex: 'start_time', key: 'start_time', ellipsis: true, },
        { title: this.$t('End-time'), dataIndex: 'end_time', key: 'end_time', ellipsis: true, },
        { title: this.$t('Elapsed-time'), dataIndex: 'consume_time', key: 'consume_time', scopedSlots: { customRender: 'time' }, ellipsis: true, },
        { title: this.$t('Detect-patterns'), dataIndex: 'type', key: 'type', scopedSlots: { customRender: 'mode' }, ellipsis: true, width: 100 },
        { title: this.$t('Inspection-situation'), dataIndex: 'status', key: 'status', scopedSlots: { customRender: 'problem' }, ellipsis: true, width: 100 },
        { title: this.$t('Results-summary'), dataIndex: 'result', key: 'result', scopedSlots: { customRender: 'result' }, ellipsis: true, width: 120 },
        { title: this.$t('Operate'), key: 'action', scopedSlots: { customRender: 'action' } },
      ],
      pagination: {
        defaultPageSize: 5,
        showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (current, pageSize) => this.pageSize = pageSize,
        buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
      },
      tableData: [
        // {record_id:'a1',problem:'sss1',star:0},
        // {record_id:'a2',problem:'sss2'},
        // {id:'a3',problem:'sss3'},
      ],
      tableData_copy: [],
      tableLoading: false,
      check_dialog: false,
      record_detail_dialog: false,
      isChecking: false,
      targetCheckRecord: {},
      screenWidth: window.screen.width,
      checkDisks: {},
      checkType: 0,
      checkingTime: '',
      checkingPercent: 0,
      detailSpinning: false,
      timer: null,
      timer2: null,
      timer3: null,
      dataSpinning: false,
      progressTimer: null,
      firstEnter: true,
      isShowTopAndCollect: false,
    }
  },
  mounted() {
    this.getCheckDisks();
    this.getCheckRecords();
    this.hideTopAndCollect();
  },
  beforeDestroy() {
    clearInterval(this.timer);
    clearInterval(this.timer2);
    clearInterval(this.progressTimer);
    clearTimeout(this.progressTimer2);
    // clearInterval(this.timer3);
  },
  watch: {
    getlanguage(val) {
      this.check_types = [
        {
          name: this.$t('Quick-check'),
          describe: this.$t('Quick-check-dec'),
          hhdDec: '8TB的HHD耗时：2分钟',
          ssdDec: '520GB的SSD耗时：1分钟',
          hhdDec_en: '8TB HDD time: 2 minutes',
          ssdDec_en: '520GB SSD time: 1 minute',
          img: require('../../../../static/images/disk_check/128_f_ic_quickcheck.png')
        },
        {
          name: this.$t('Deep-check'),
          describe: this.$t('Deep-check-dec'),
          hhdDec: '8TB的HHD耗时：35分钟',
          ssdDec: '520GB的SSD耗时：2分钟',
          hhdDec_en: '8TB HDD time: 35 minutes',
          ssdDec_en: '520GB SSD time: 2 minutes',
          img: require('../../../../static/images/disk_check/128_f_ic_depthcheck.png')
        },
      ]
      this.radio_values = [
        { name: this.$t('All'), value: 'all' },
        { name: this.$t('Quick-check'), value: 'quick' },
        { name: this.$t('Deep-check'), value: 'deep' },
      ]
      this.rangePickerLocal = {
        "lang": {
          "placeholder": "Select date",
          "rangePlaceholder": ["Start date", "End date"],
          "today": "Today",
          "now": "Now",
          "backToToday": "Back to today",
          "ok": this.$t('Sure'),
          "clear": "Clear",
          "month": "Month",
          "year": "Year",
          "timeSelect": this.$t('Select-time-picker'),
          "dateSelect": this.$t('Select-date-picker'),
          "monthSelect": "Choose a month",
          "yearSelect": "Choose a year",
          "decadeSelect": "Choose a decade",
          "yearFormat": "YYYY",
          "dateFormat": "M/D/YYYY",
          "dayFormat": "D",
          "dateTimeFormat": "M/D/YYYY HH:mm:ss",
          "monthFormat": "MMMM",
          "monthBeforeYear": true,
          "previousMonth": "Previous month (PageUp)",
          "nextMonth": "Next month (PageDown)",
          "previousYear": "Last year (Control + left)",
          "nextYear": "Next year (Control + right)",
          "previousDecade": "Last decade",
          "nextDecade": "Next decade",
          "previousCentury": "Last century",
          "nextCentury": "Next century"
        }
      }
      this.columns = [
        { title: this.$t('Record') + 'ID', dataIndex: 'record_id', key: 'record_id', scopedSlots: { customRender: 'id' }, width: 200, ellipsis: true, },
        { title: this.$t('Start-time'), dataIndex: 'start_time', key: 'start_time', ellipsis: true, },
        { title: this.$t('End-time'), dataIndex: 'end_time', key: 'end_time', ellipsis: true, },
        { title: this.$t('Elapsed-time'), dataIndex: 'consume_time', key: 'consume_time', scopedSlots: { customRender: 'time' }, ellipsis: true, },
        { title: this.$t('Detect-patterns'), dataIndex: 'type', key: 'type', scopedSlots: { customRender: 'mode' }, ellipsis: true, width: 100 },
        { title: this.$t('Inspection-situation'), dataIndex: 'status', key: 'status', scopedSlots: { customRender: 'problem' }, ellipsis: true, width: 100 },
        { title: this.$t('Results-summary'), dataIndex: 'result', key: 'result', scopedSlots: { customRender: 'result' }, ellipsis: true, width: 120 },
        { title: this.$t('Operate'), key: 'action', scopedSlots: { customRender: 'action' } },
      ]
    },
    // isChecking(newValue) {
    //   if(newValue) {
    //     //初始调用动画函数
    //     this.$nextTick(() => {
    //       this.progressAnimate();
    //     })
    //   }
    // }
  },
  computed: {
    getlanguage() {
      return this.$store.state.language
    },
  },
  methods: {
    //只有查看权限时，隐藏置顶和收藏
    hideTopAndCollect() {
      let auth = JSON.parse(localStorage.getItem('tags'));
      if (auth.indexOf('E8') != -1) {//有磁盘检测权限
        let count = 0;
        auth.forEach(item => {
          if (item.indexOf('E8') != -1) {
            count++;
          }
        })
        if (auth.indexOf('E8-1') && count == 2) {
          this.isShowTopAndCollect = false;
        } else {
          this.isShowTopAndCollect = true;
        }
      }
    },

    //获取要检测的磁盘
    getCheckDisks() {
      request('get', 'diskhealth/disk_mess').then(res => {
        // console.log('获取检测的磁盘', res)
        if (res.data.success) {
          this.checkDisks = res.data.data;
        } else {
          if (this.$store.state.language == 'zh') {
            this.$message.error('获取检测的磁盘列表失败！')
          } else {
            this.$message.error('Failed to get the detected disk list!')
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },

    //获取表格数据以及当前是否正在检测
    getCheckRecords() {
      this.dataSpinning = true;
      request('get', 'diskhealth/health/record').then(res => {
        // console.log('获取检测记录', res)
        if (res.data.flag == 1) {
          this.model(res.data.id) //返回模板
          this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
        }
        this.tableData = [];
        this.tableData_copy = [];
        this.tableData = res.data.records;
        this.tableData_copy = res.data.records;
        if (res.data.checking) {//是否存在检测任务
          this.isChecking = true;
          this.getCheckStatus();
          clearInterval(this.timer2);
          this.timer2 = setInterval(() => {
            this.getCheckStatus();
          }, 1000 * 15)
        }
        this.filterTableData();
      }).catch(err => {
        console.log(err);
      }).finally(() => {
        this.dataSpinning = false;
      })
    },

    //实时获取检测状态
    getCheckStatus() {
      clearInterval(this.progressTimer);
      request('get', 'diskhealth/health/real_time').then(res => {
        // console.log('获取检测状态', res)
        if (res.data.success) {
          // if(res.data.percent == 100) {
          //   clearInterval(this.timer);
          //   clearInterval(this.timer2);
          //   this.isChecking = false;
          //   return
          // }
          this.checkingTime = res.data.use_time;
          let percent_value = res.data.percent == 0 ? 0 : res.data.percent;
          if (this.firstEnter) {
            this.checkingPercent = Math.ceil(percent_value);
            this.firstEnter = false;
          } else {
            this.progressTimer = setInterval(() => {
              if (percent_value != 0 && this.checkingPercent < percent_value) {
                this.checkingPercent = Math.ceil(this.checkingPercent);
                if (Math.ceil(this.checkingPercent) + Math.ceil(percent_value / 15) > percent_value) {
                  this.checkingPercent = percent_value;
                } else {
                  this.checkingPercent = Math.ceil(this.checkingPercent) + Math.ceil(percent_value / 15);
                }
              } else {
                this.checkingPercent = percent_value;
              }
              // if(percent_value %1 === 0) {//是整数
              //   this.checkingPercent = percent_value;
              // }else {
              //   this.checkingPercent = Number(percent_value).toFixed(2);
              // }
            }, 1000)
          }
          this.checkType = res.data.check_type;
          // this.$nextTick(() => {
          //   this.progressAnimate();
          // })
        } else {
          clearInterval(this.progressTimer);
          this.progressTimer = setInterval(() => {
            this.checkingPercent = Math.ceil(this.checkingPercent) + Math.ceil(100 / 15);
            if (this.checkingPercent >= 100) {
              clearInterval(this.timer);
              clearInterval(this.timer2);
              clearInterval(this.progressTimer);
              this.getCheckDisks();
              this.getCheckRecords();
              this.isChecking = false;
              this.checkType = 0;
              this.checkingTime = '';
              this.checkingPercent = 0;
              if (this.$store.state.language == 'zh') {
                this.$message.success('磁盘检测完成！');
              } else {
                this.$message.success('Disk detection completed!');
              }
            }
          }, 1000)
        }
      }).catch(err => {
        console.log(err);
      })
    },


    //筛选方法
    filterTableData() {
      // this.error_check_value
      // this.collect_check_value
      // this.check_mode
      // this.checkTime
      if (!this.error_check_value && !this.collect_check_value && this.check_mode == 'all' && this.checkTime.length == 0) {
        this.tableData = this.tableData_copy;
        return;
      }
      let finalData = this.tableData_copy;
      if (this.error_check_value) { //现在是仅显示故障记录  以前!this.error_check_value(显示故障记录)
        finalData = this.tableData_copy.filter(item => {
          return item.result == +this.error_check_value;
          // 故障result：(0-未发生故障，1-发生故障)
        })
      }
      if (this.collect_check_value) { //现在是仅显示收藏  以前!this.collect_check_value(显示收藏)
        finalData = finalData.filter(item => {
          return item.star == 1;
          // return item.star == +this.collect_check_value;
          // 收藏star(0-非关注，1-关注)
        })
      }
      if (this.check_mode != 'all') {
        finalData = finalData.filter(item => {
          return item.type == this.check_mode;
          // 模式type(0--短检测。1--长检测)
        })
      }
      if (this.checkTime.length != 0) {
        finalData = finalData.filter(item => {
          // 将时间字符串'2022-07-22 13:45:44'转为时间戳
          let end_time = getTimestampFromString(item.end_time) / 1000;
          // return item.开始时间 >= this.checkTime[0].unix() && item.结束时间 <= this.checkTime[1].unix()
          return end_time >= this.checkTime[0].unix() && end_time <= this.checkTime[1].unix();
        })
      }
      this.tableData = finalData;
    },

    //打开检测窗口
    handleCheck(index) {
      this.checkType = index;
      this.check_dialog = true;
    },

    //中断检测
    handleStopCheck() {
      let _this = this;
      this.$confirm({
        title: this.$t('Break-detect'),
        content: this.$t('Cancel-check-tip'),
        cancelText: this.$t('Cancel'),
        okText: this.$t('Break-detect'),
        okType: "danger",
        icon: 'close-circle',
        onOk() {
          request('post', 'diskhealth/health/stop').then(res => {
            // console.log('中断磁盘检测', res)
            if (res.data.success) {
              clearInterval(_this.timer);
              clearInterval(_this.timer2);
              clearInterval(_this.progressTimer);
              _this.checkType = 0;
              _this.checkingTime = '';
              _this.checkingPercent = 0;
              _this.getCheckRecords();
              _this.isChecking = false;
              _this.$message.success(_this.$t('Interrupt-disk-check-ok'));
            } else {
              _this.$message.error(_this.$t('Interrupt-disk-check-no'));
            }
          }).catch(err => {
            console.log(err);
          })
        },
        onCancel() { },
      });
    },

    //canvas画进度图 https://www.jb51.net/article/236895.htm
    drawProgress(canvasDom, ctx, steps) {
      //找到画布的中心点
      let canvasX = canvasDom.width / 2;
      let canvasY = canvasDom.height / 2;
      //进度条是100%，所以要把一圈360度分成100份
      let progress = Math.PI * 2 / 100;
      //指定初始加载步长
      // let steps = 0.5;
      //3.绘制环形底层
      ctx.strokeStyle = '#dddddd';
      ctx.lineWidth = 15;
      ctx.save();
      ctx.beginPath();
      ctx.arc(canvasX, canvasY, 60, 0, Math.PI * 2, false)
      ctx.stroke();
      ctx.closePath();
      ctx.restore();
      //4.绘制进度层
      ctx.strokeStyle = "#059db3";
      ctx.lineWidth = 15;
      ctx.save();
      ctx.beginPath();
      ctx.arc(canvasX, canvasY, 60, -Math.PI / 2, -Math.PI / 2 + steps * progress, false);
      ctx.stroke();
      ctx.closePath();
      ctx.restore();
      //5.绘制字体并指定位置
      ctx.fillStyle = "#000000"; //可改
      ctx.font = "bold 16px Arial"; //可改
      ctx.save();
      // canvasX-30, canvasY+10  中的加减的数值可改
      if (steps.toFixed(0).length == 2) {
        ctx.fillText(steps.toFixed(0) + '%', canvasX - 10, canvasY + 5);
      } else {
        ctx.fillText(steps.toFixed(0) + '%', canvasX - 8, canvasY + 5);
      }
      ctx.restore();
    },
    //动画函数
    progressAnimate() {
      let mycanvas = document.getElementById('mycanvas');
      let ctx = mycanvas.getContext('2d');
      //执行平滑动画
      // window.requestAnimationFrame(() => {
      //   //判断步子最终走多远的边界值，此值可以改
      //   if (this.checkingPercent < 90) {
      //   //该函数在边界内可以调用
      //     this.progressAnimate();
      //   }
      // });
      clearInterval(this.timer3)
      this.timer3 = setInterval(() => {
        if (this.checkingPercent < 99) {
          //该函数在边界内可以调用
          this.progressAnimate();
        }
      }, 1000)
      //清空绘制内容
      ctx.clearRect(0, 0, mycanvas.width, mycanvas.height);
      //每次增加的步长，数值越大步子越大跑的越快，数值越小走的越慢
      this.checkingPercent += 0.5;//可改
      //调用绘制形状函数，传入参数绘制对象，环形进度步长
      this.drawProgress(mycanvas, ctx, this.checkingPercent);
    },

    //关闭检测窗口
    closeDialog() {
      this.check_dialog = false;
    },

    //关闭检测报告窗口
    closeDrawer() {
      this.record_detail_dialog = false;
    },

    //改变故障记录多选框
    changeErrorCheck() {
      this.filterTableData();
    },

    //改变收藏多选框
    changeCollectCheck() {
      this.filterTableData();
    },

    //改变检测模式单选框组
    changeCheckMode() {
      this.filterTableData();
    },

    //改变检测结束时间
    changeCheckTime(date, dateString) {
      //moment对象转为时间戳：date[0].unix()
      // console.log('333333333', date[0].unix())
      // this.check_end_time_string = dateString;
      this.filterTableData();
    },
    handleCheckEndTime() {
      this.filterTableData();
    },
    //解决清空时间
    handleClearTime(value) {
      if (value.length == 0) {
        this.filterTableData();
      }
    },

    //获取单个磁盘检测报告
    getDiskCheckRecord(record) {
      return new Promise((resolve, reject) => {
        request('get', 'diskhealth/health/report', {
          // params: {
          record_id: record.record_id
          // }
        }).then(res => {
          // console.log('单个磁盘检测报告', res)
          resolve(res);
        }).catch(err => {
          reject(err)
          console.log(err)
        })
      })
    },

    //检测记录详情
    async showDetail(record, type, status) {
      if (record.read_status == 0) {
        await this.toOperateStatus(record, type, status); //标志已读了
      }
      //获取磁盘检测报告
      let diskRecord = await this.getDiskCheckRecord(record);
      if (diskRecord.data.flag && diskRecord.data.flag == 1) {
        this.model(diskRecord.data.id) //返回模板
        this.notice(diskRecord.data.id, diskRecord.data.params, diskRecord.data.flag) //通知列表显示
      } else {
        this.targetCheckRecord = diskRecord.data;
        this.record_detail_dialog = true;
      }
      // this.detailSpinning = true;
    },

    //置顶、收藏、已读操作
    toOperateStatus(record, type, status) {
      request('post', 'diskhealth/update_status', {
        record_id: record.record_id,
        key: type,
        status: status
      }).then(res => {
        // console.log('标志位操作', res);
        if (res.data.success) {
          this.getCheckRecords();
          if (type != 'read') {
            this.$message.success(this.$t('Operate-ok'));
          }
        } else {
          if (res.data.msg.indexOf('more than 5') != -1) {
            this.$message.error(this.$t('Top-error-tip'));//最多置顶5条记录
          } else {
            if (type != 'read') {
              this.$message.error(this.$t('Operate-no'));
            }
          }
        }
      }).catch(err => {
        console.log(err);
      })
    },

    //删除检测记录
    delCheckRecord(record) {
      let _this = this;
      const ch_content = `删除检测记录“${record.record_id}”后，该记录将无法恢复！您确定要删除吗？`;
      const en_content = `After a detection record is deleted, it cannot be recovered! Are you sure you want to delete it:"${record.id}"? `;
      this.$confirm({
        title: this.$t('Delete-detection-Record'),
        content: this.$store.state.language == 'en' ? en_content : ch_content,
        cancelText: this.$t('Cancel'),
        okText: this.$t('Delete'),
        okType: "danger",
        icon: 'close-circle',
        onOk() {
          request('DELETE', 'diskhealth/health/record', {
            // data: {
            record_id: record.record_id
            // }
          }).then(res => {
            _this.model(res.data.id) //返回模板
            _this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
            _this.getCheckRecords();
            // if(res.data.flag == 0) {
            //   _this.getCheckRecords();
            //   _this.$message.success(res.data.msg);
            // }else {
            //   _this.$message.error(res.data.msg);
            // }
          }).catch(err => {
            console.log(err);
          })
        },
        onCancel() { },
      });
    },

    //是否开始检测磁盘
    isCheckingDisk(payload) {
      this.isChecking = payload;
      if (this.isChecking) {
        this.timer = setInterval(() => {
          this.getCheckStatus();
        }, 1000 * 15)
      }
    },
  },
}
</script>

<style scoped>
.content-box {
  margin: 1em;
}

.top-tip {
  padding: 10px;
  background-color: rgba(7, 133, 253, 0.1);
  border-radius: 4px;
  border: solid 1px var(--themeColor);
  margin: 0 15px;
}

.top-tip img {
  margin-right: 5px;
  vertical-align: text-bottom;
}

.text-weight {
  font-weight: 700;
}

.top-check-content,
.top-check-content2 {
  position: relative;
  width: 100%;
  height: 100%;
  box-shadow: 1px 2px 10px 0px rgba(0, 0, 0, 0.2);
  padding-top: 15px;
  background-color: #fff;
}

.top-check-content2 {
  animation: fadeInOut 0.7s 1;
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

.split-line {
  position: absolute;
  width: 1px;
  height: 140px;
  left: 50%;
  top: 30%;
  background: #cdcdcd;
  transform: translateX(-50%);
}

.check-type-box,
.check-type-box2 {
  display: inline-block;
  width: 50%;
  height: 100%;
  background-color: #fff;
  padding: 15px;
  /* box-shadow: 1px 2px 10px 0px rgba(0, 0, 0, 0.2); */
}

.check-type-box2 {
  vertical-align: top;
  height: 150px;
  background-color: transparent;
}

.check-title {
  font-weight: 700;
  color: #333;
  font-size: 20px;
}

.quick-btn,
.deep-btn {
  background-color: var(--mainGreenColor);
  color: #fff;
  width: 144px;
  height: 40px;
  float: right;
}

.deep-btn {
  background-color: var(--themeColor);
}

.check-desc {
  margin: 20px 0 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  word-break: break-all;
}

.check-hhdtip,
.check-ssdtip {
  color: var(--themeColor);
  background-color: rgba(7, 133, 253, 0.1);
  border-radius: 4px;
  padding: 5px;
  margin: 0 10px;
}

.check-ssdtip {
  color: #6772e5;
  background-color: rgba(103, 114, 229, 0.1);
  margin-left: 0;
}

.bottom-check-record {
  height: 100%;
  margin: 15px 0;
  background-color: #fff;
  box-shadow: 1px 2px 10px 0px rgba(0, 0, 0, 0.2);
}

.disk-check-record-title {
  padding: 10px 0;
  border-bottom: 1px solid #cdcdcd;
}

.disk-check-record-title span {
  border-left: 2px solid var(--themeColor);
  padding-left: 10px;
}

.check-table-box {
  padding: 15px;
}

.check-filter-box {
  display: flex;
  justify-content: flex-end;
}

.check-filter-box span {
  line-height: 32px;
  margin-right: 30px;
}

.check-table {
  margin: 15px 0;
}

.oper-btn img {
  cursor: pointer;
  margin: 0 5px;
}

.time-tip {
  color: var(--themeColor);
}

.en-check-desc {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.tip-img {
  width: 16px;
  height: 16px;
}


@media screen and (min-width:1920px) {
  .content-box {
    margin: 1.5em;
  }

  .check-type-box,
  .check-type-box2 {
    padding: 20px;
  }

  /* .bottom-check-record {
    height: 590px;
  } */
}
</style>